package solutions.leetcode.normal;

import solutions.lib.BaseSolution;

/**
 * @author lizhidong
 * <a href="https://leetcode-cn.com/problems/monotone-increasing-digits/">738.单调递增的数字</a>
 */
public class Solution738 extends BaseSolution {

    public int monotoneIncreasingDigits(int n) {
        char[] chars = String.valueOf(n).toCharArray();
        for (int i = 0; i < chars.length - 1; i++) {
            if (chars[i] > chars[i + 1]) {
                int p;
                for (p = i - 1; p >= 0; p--) {
                    if (chars[p] < chars[i]) {
                        break;
                    }
                }
                p++;
                chars[p]--;
                for (int j = p + 1; j < chars.length; j++) {
                    chars[j] = '9';
                }
            }
        }
        return Integer.parseInt(String.valueOf(chars));
    }

    public static void main(String[] args) {
        Solution738 solution = new Solution738();
        System.out.println(solution.monotoneIncreasingDigits(332));
    }
}